package com.xzakota.minesweeper.db;

import com.xzakota.minesweeper.RoomAtServer;
import com.xzakota.minesweeper.log.XLogger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * room 数据库访问实现
 *
 * @author Xzakota
 */
public class RoomDaoImpl {
    /**
     * @return 查找所有房间
     */
    public static Map<Integer, RoomAtServer> getAllRoom() {
        Connection conn = ConnectionManager.getConnection();
        String sql = "SELECT * FROM room";
        PreparedStatement pStatement = null;
        ResultSet resultSet = null;
        Map<Integer, RoomAtServer> map = new HashMap<>();
        try {
            pStatement = conn.prepareStatement(sql);
            resultSet = pStatement.executeQuery();
            while (resultSet.next()) {
                int roomNum = resultSet.getInt("num");
                RoomAtServer room = new RoomAtServer(roomNum);
                room.roomLevel = resultSet.getInt("level");

                map.put(roomNum, room);
            }
            return map;
        } catch (SQLException e) {
            XLogger.error(e);
            return map;
        } finally {
            ConnectionManager.release(resultSet, pStatement, conn);
        }
    }

    /**
     * 通过房间号查询房间难易等级
     *
     * @param roomNum 房间号
     * @return 房间难易等级
     */
    public static int queryLevel(int roomNum) {
        Connection conn = ConnectionManager.getConnection();
        String sql = "SELECT * FROM room WHERE num = ?";
        PreparedStatement pStatement = null;
        ResultSet resultSet = null;
        try {
            pStatement = conn.prepareStatement(sql);
            pStatement.setInt(1, roomNum);
            resultSet = pStatement.executeQuery();
            if (resultSet.next()) {
                return resultSet.getInt("level");
            } else {
                return -1;
            }
        } catch (SQLException e) {
            XLogger.error(e);
            return -1;
        } finally {
            ConnectionManager.release(resultSet, pStatement, conn);
        }
    }
}
